import React, { useEffect, useRef, useState } from "react";
import { Popup, NavBar, Input, Card, IndexBar, List } from "antd-mobile";
import { citySet } from "../../../reducers/citySlice";
import { useDispatch } from "react-redux";
import http from "../../../utils/http";

import AMapLoader from "@amap/amap-jsapi-loader";
import useDebounce from "../../../hooks/useDebounce";

function CityPopup({ visible2, setVisible2, type }) {
    const dispatch = useDispatch();
    const searchInputRef = useRef(null)

    const [cityMy, setCityMy] = useState("");
    const [groups, setGroups] = useState([]);
    const [hotCities, setHotCities] = useState([]);
    const [searchList,setSearchList] = useState([]);

    const getCity = async () => {
        const res = await http.get("/api/city");
        const { code, data } = res.data;

        if (code == 200) {
            setGroups(data.city);
            setHotCities(data.hotCities);
        }
    };

    useEffect(() => {
        getCity();
    }, []);

    const setCity = (city) => {
        dispatch(citySet({ type: type, value: city }));
        setVisible2(false);
    };

    useEffect(() => {
        window._AMapSecurityConfig = {
            securityJsCode: "5e6a347db9a67e214d1ae236639f106d",
        };
        AMapLoader.load({
            key: "fd1a5cc00cbbd6c96e9b91e893479a57", // 申请好的Web端开发者Key，首次调用 load 时必填
            version: "2.0", // 指定要加载的 JSAPI 的版本，缺省时默认为 1.4.15
            plugins: ["AMap.Scale"], //需要使用的的插件列表，如比例尺'AMap.Scale'，支持添加多个如：['...','...']
        })
            .then((AMap) => {
                // 这里写地图的操作

                AMap.plugin("AMap.CitySearch", function () {
                    var citySearch = new AMap.CitySearch();
                    citySearch.getLocalCity(function (status, result) {
                        if (status === "complete" && result.info === "OK") {
                            // 查询成功，result即为当前所在城市信息
                            console.log("result", result);
                            setCityMy(result.city);
                        }
                    });
                });
            })
            .catch((e) => {
                console.log(e);
            });
    }, []);

    const searchChange = useDebounce(async (e) => {
        const value = e.target.value
        const res = await http.get('/api/city/search', {params: {wd: value}})

        const {code, data} = res.data 

        if(code === 200) {
           setSearchList( data )
        }
    }, 800)

    return (
        <Popup
            visible={visible2}
            onMaskClick={() => {
                setVisible2(false);
            }}
            onClose={() => {
                setVisible2(false);
            }}
            bodyStyle={{
                height: "100vh",
                width: "100vw",
                display: "flex",
                flexDirection: "column",
            }}
        >
            <NavBar
                onBack={() => {
                    setVisible2(false);
                }}
            >
                <input className="input_search" placeholder="请输入城市" ref={searchInputRef} onChange={searchChange} />
            </NavBar>
            <div className="searchList">
                <div>
                    {searchList.map((item, index) => {
                        return (
                            <div className="searchItem" key={index} onClick={() => {
                                setCity(item.name);
                                setSearchList([]);
                                console.log(searchInputRef.current)
                                searchInputRef.current.value = ''
                            }}>
                                {item.name}
                            </div>
                        )
                    })}
                </div>
            </div>

            <div className="city_postion">
                当前定位：{" "}
                <span
                    onClick={() => {
                        setCity(cityMy);
                    }}
                >
                    {cityMy}
                </span>
            </div>
            <Card className="hot_box">
                <h3>热门</h3>
                <div className="hot_flex">
                    {
                        hotCities.map((item, index) => {
                            return (
                                <span
                                    key={index}
                                    onClick={() => {
                                        setCity(item.name);
                                    }}
                                >
                                    {item.name}
                                </span>
                            );
                        })
                    }
                </div>
            </Card>
            <IndexBar>
                {groups.map((group) => {
                    const { initial, list } = group; 
                    return (
                        <IndexBar.Panel
                            index={initial}
                            title={`标题${initial}`}
                            key={`标题${initial}`}
                        >
                            <List>
                                {list.map((item, index) => (
                                    <List.Item
                                        key={index}
                                        onClick={() => {
                                            setCity(item.name);
                                        }}
                                    >
                                        {item.name}
                                    </List.Item>
                                ))}
                            </List>
                        </IndexBar.Panel>
                    );
                })}
            </IndexBar>
        </Popup>
    );
}

export default CityPopup;
